package com.dlwx.parttimetalent.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dlwx.parttimetalent.AlPay.AliPayUtiles;
import com.dlwx.parttimetalent.R;
import com.dlwx.parttimetalent.adapter.NoTimeAdapter;
import com.dlwx.parttimetalent.base.BaseActivity;
import com.dlwx.parttimetalent.bean.AliPayResBean;
import com.dlwx.parttimetalent.bean.ConfirmOrderBean;
import com.dlwx.parttimetalent.bean.TotalPriceBean;
import com.dlwx.parttimetalent.bean.WXPAtResultBean;
import com.dlwx.parttimetalent.comm.Constant;
import com.dlwx.parttimetalent.comm.Http;
import com.dlwx.parttimetalent.inter.DialogInter;
import com.dlwx.parttimetalent.inter.DialogPayInter;
import com.dlwx.parttimetalent.inter.GetAgeInter;
import com.dlwx.parttimetalent.utils.DealResult;
import com.dlwx.parttimetalent.utils.OkgoUtil;
import com.dlwx.parttimetalent.utils.SPUtils;
import com.dlwx.parttimetalent.utils.ScreenUtils;
import com.dlwx.parttimetalent.utils.SizeUtils;
import com.dlwx.parttimetalent.utils.ToastUtils;
import com.dlwx.parttimetalent.views.AgeDialog;
import com.dlwx.parttimetalent.views.ClockDialog;
import com.dlwx.parttimetalent.views.PayTypeDialog;
import com.dlwx.parttimetalent.views.TimeOrderDialog;
import com.dlwx.parttimetalent.wechatpay.WeChatPayUtiles;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

public class ConfirmOrderActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.iamge_header)
    CircleImageView iamgeHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_grade)
    TextView tvGrade;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.et_day_start)
    TextView etDayStart;
    @BindView(R.id.et_time_start)
    TextView etTimeStart;

    @BindView(R.id.flowlayout_money)
    TagFlowLayout flowlayoutMoney;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.tv_project)
    TextView tvProject;
    @BindView(R.id.recyclerView)
    LRecyclerView recyclerView;
    @BindView(R.id.title_left_two_tv)
    TextView titleLeftTwoTv;
    @BindView(R.id.tv_adress)
    EditText tvAdress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.flowlayout_time)
    TagFlowLayout flowlayoutTime;
    @BindView(R.id.tv_time_start)
    TextView tvTimeStart;
    private int itemWidth;

    private String curruserId;
    private String labelType;
    private String labeId;
    private NoTimeAdapter mAdapter;
    private double totalPrice, countPrice = 0;
    private TagAdapter<ConfirmOrderBean.BodyBean.RewardlistBean> tagAdapter1;
    //    自定义打赏金额
    private Integer cusPrice = 0;
    //    标签打赏金额
    private Integer rewardPrice = 0;
    private TagAdapter<String> tagAdapterTime;
    private String cityStr;
    private String selectnum;
    private String timetype;
    private String order_area;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_confirm_order);
        int width = ScreenUtils.getScreenWidth();
        itemWidth = (int) (width - SizeUtils.dp2px(40f)) / 5;
        ButterKnife.bind(this);
        initView();
        getDatas();
    }

    private void getDatas() {
        String longi = (String) SPUtils.get(ConfirmOrderActivity.this, Constant.LOCATION_LON, "116.395645");
        String lat = (String) SPUtils.get(ConfirmOrderActivity.this, Constant.LOCATION_LAT, "39.929985");
        loadingDialog.show();
        OkgoUtil.post(Http.GetConfirmOrderInfo, ConfirmOrderActivity.this)
                .params("curruserid", curruserId)
                .params("labelid", labeId)
                .params("labeltype", labelType)
                .params("long", longi)
                .params("lat", lat)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        ConfirmOrderBean parentBean = DealResult.getInstance().dealDatas(ConfirmOrderActivity.this, response, new TypeToken<ConfirmOrderBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {
                            setDatas(parentBean.getBody());
                        } else {
                            ToastUtils.toastForShort(ConfirmOrderActivity.this, parentBean.getResult());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

    private void setDatas(ConfirmOrderBean.BodyBean body) {
        ConfirmOrderBean.BodyBean.UserinfoBean userInfo = body.getUserinfo();
        Glide.with(this).load(userInfo.getHeadurl()).into(iamgeHeader);
        String remarkName = userInfo.getRemarkName();
        if (TextUtils.isEmpty(remarkName)) {
            tvName.setText(userInfo.getNickname());
        } else {
            tvName.setText(remarkName);
        }
        tvAddress.setText("距离：" + userInfo.getRange());
        ConfirmOrderBean.BodyBean.WorklistBean workInfo = body.getWorklist();
        final List<String> times = new ArrayList<>();
        if (workInfo != null) {
            tvGrade.setText(workInfo.getScore() + "分");
            if (workInfo.getLabeltime() == 1) {
                timetype="1";
                times.add("1天");
                times.add("2天");
                times.add("3天");
                times.add("4天");
                tvTimeStart.setVisibility(View.GONE);
                etTimeStart.setVisibility(View.GONE);
                tvPrice.setText(workInfo.getLabelprice() + "元" + "/天（"+workInfo.getMintime()+"天起)");
            } else {
                timetype="2";
                times.add("1小时");
                times.add("2小时");
                times.add("3小时");
                times.add("4小时");
                tvPrice.setText(workInfo.getLabelprice() + "元" + "/小时("+workInfo.getMintime()+"小时起)");
            }
            tvProject.setText(workInfo.getLabelname());
        }
        times.add("自定义");
        final List<ConfirmOrderBean.BodyBean.RewardlistBean> rewards = body.getRewardlist();
        List<ConfirmOrderBean.BodyBean.BkyyBean> noTimeBeans = body.getBkyy();
        mAdapter.addAll(noTimeBeans);
        recyclerView.refreshComplete(mAdapter.getItemCount());
        flowlayoutTime.setMaxSelectCount(1);
        tagAdapterTime = new TagAdapter<String>(times) {
            @Override
            public View getView(FlowLayout parent, int position, String str) {
                TextView textView = (TextView) LayoutInflater.from(ConfirmOrderActivity.this)
                        .inflate(R.layout.tv_label_red_select, flowlayoutMoney, false);
                textView.setText(str);
                textView.getLayoutParams().width = itemWidth;
                return textView;
            }
        };
        flowlayoutTime.setAdapter(tagAdapterTime);

        flowlayoutTime.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(final View view, int position, FlowLayout parent) {
                Set<Integer> sets = flowlayoutTime.getSelectedList();
                if(sets.isEmpty()){
                    countPrice=0;
                    totalPrice=cusPrice+rewardPrice+countPrice;
                    tvConfirm.setText("提交订单(共计" + totalPrice + "元)");
                    return false;
                }
                if (position == 4) {
                    TimeOrderDialog dialog;
                    if (times.get(0).contains("天")) {
                        dialog = new TimeOrderDialog(ConfirmOrderActivity.this, true, new DialogInter() {
                            @Override
                            public void getInfo(String data) {
                                selectnum = data.substring(0, data.length() -1);
                                times.remove(4);
                                times.add(data);
                                tagAdapterTime.notifyDataChanged();
                                tagAdapterTime.setSelectedList(4);
                                countTotalPrice();
                            }

                            @Override
                            public void getWorkInfo(String start, String end, String unit) {

                            }
                        });
                    } else {
                        dialog = new TimeOrderDialog(ConfirmOrderActivity.this, false, new DialogInter() {
                            @Override
                            public void getInfo(String data) {
                                selectnum = data.substring(0, data.length() - 2);
                                times.remove(4);
                                times.add(data);
                                tagAdapterTime.notifyDataChanged();
                                tagAdapterTime.setSelectedList(4);
                                countTotalPrice();
                            }

                            @Override
                            public void getWorkInfo(String start, String end, String unit) {

                            }
                        });

                    }
                    dialog.show();
                }else{
                    selectnum=times.get(position).substring(0,1);
                    countTotalPrice();
                }
                return false;
            }
        });
        flowlayoutMoney.setMaxSelectCount(1);
        tagAdapter1 = new TagAdapter<ConfirmOrderBean.BodyBean.RewardlistBean>(rewards) {
            @Override
            public View getView(FlowLayout parent, int position, ConfirmOrderBean.BodyBean.RewardlistBean rewardlistBean) {
                String tip = rewardlistBean.getPrice() + "元";
                TextView textView = (TextView) LayoutInflater.from(ConfirmOrderActivity.this)
                        .inflate(R.layout.tv_label_red_select, flowlayoutMoney, false);
                textView.setText(tip);
                textView.getLayoutParams().width = itemWidth;
                return textView;
            }
        };
        flowlayoutMoney.setAdapter(tagAdapter1);
        flowlayoutMoney.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Set<Integer> sets = flowlayoutMoney.getSelectedList();
                if (!sets.isEmpty()) {
                    for (Integer pos : sets) {
                        rewardPrice = Integer.valueOf(rewards.get(position).getPrice());
                        totalPrice = countPrice + rewardPrice + cusPrice;
                        tvConfirm.setText("提交订单(共计" + totalPrice + "元)");
                    }
                } else {
                    rewardPrice = 0;
                    totalPrice = countPrice + rewardPrice + cusPrice;
                    tvConfirm.setText("提交订单(共计" + countPrice + "元)");
                }
                return false;
            }
        });

    }

    private void initView() {
        curruserId = getIntent().getStringExtra("curruserId");
        labeId = getIntent().getStringExtra("labeId");
        labelType = getIntent().getStringExtra("labelType");
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        tvMiddleTitle.setVisibility(View.VISIBLE);
        tvMiddleTitle.setText("提交订单");
        String address = (String) SPUtils.get(this, Constant.ADDRESS, "");
        cityStr = (String) SPUtils.get(this, Constant.CITY, "");
//        tvAdress.setText(address);
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() < 0) {
                    return;
                }
                if (TextUtils.isEmpty(etMoney.getText().toString())) {
                    cusPrice = 0;
                } else {

                    cusPrice = Integer.valueOf(etMoney.getText().toString());
                }
                totalPrice = countPrice + rewardPrice + cusPrice;
                tvConfirm.setText("提交订单(共计" + totalPrice + "元)");
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new NoTimeAdapter(this);
        mAdapter.setDataList(new ArrayList<ConfirmOrderBean.BodyBean.BkyyBean>());
        LRecyclerViewAdapter lRecyclerViewAdapter = new LRecyclerViewAdapter(mAdapter);
        recyclerView.setAdapter(lRecyclerViewAdapter);
        recyclerView.setPullRefreshEnabled(false);
        recyclerView.setLoadMoreEnabled(false);
    }

    @OnClick({R.id.title_left_one_btn, R.id.tv_confirm, R.id.et_day_start, R.id.et_time_start, R.id.ll_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                this.finish();
                break;
            case R.id.ll_address:
//                Intent i = new Intent(this, MapChooseActivity.class);
//                startActivityForResult(i, 0);
                break;
            case R.id.tv_confirm:
//               startDate=etDayStart.getText().toString();
                if(TextUtils.isEmpty(etDayStart.getText().toString())){
                    ToastUtils.toastForShort(this,"请先选择开始时间");return;
                }
                if(countPrice==0){
                    ToastUtils.toastForShort(this,"请选择下单时间");return;
                }
                order_area=tvAdress.getText().toString();
                if(TextUtils.isEmpty(order_area)){
                    ToastUtils.toastForShort(this,"请输入任务/工作地址");return;
                }
                startTime=etTimeStart.getText().toString();
                PayTypeDialog dialog = new PayTypeDialog(this, new DialogPayInter() {
                    @Override
                    public void payType(int payType) {
                        payOrder(payType);
//                        switch (payType) {
//                            case 1:
//                                payOrder(payType);
//                                break;
//                            case 2:
//                                payOrder(payType);
//                                break;
//                            case 3:
//                                PayPswDialog dialog = new PayPswDialog(ConfirmOrderActivity.this, new DialogFilerInter() {
//                                    @Override
//                                    public void callBack(String datas, String labeid, String sex, String minage, String maxage, String distance) {
////                                        yuePay(3,datas);
//                                    }
//                                });
//                                dialog.show();
//                                break;
//                        }
                    }
                });
                dialog.show();
                break;
            case R.id.et_day_start:
                AgeDialog ageDialog1 = new AgeDialog(this, new GetAgeInter() {
                    @Override
                    public void getAge(int year, int month, int day, String start) {
                        etDayStart.setText(year + "年" + month + "月" + day + "日");
                        startDate=year + "." + month + "." + day ;
                    }
                },true);
                ageDialog1.show();
                break;
            case R.id.et_time_start:
                if (TextUtils.isEmpty(etDayStart.getText().toString())) {
                    ToastUtils.toastForShort(this, "请先选择开始日期");
                    return;
                }
                ClockDialog ageDialog2 = new ClockDialog(this, new GetAgeInter() {
                    @Override
                    public void getAge(int year, int month, int day, String start) {
                        String yearStr="";
                        if(year<10){
                            yearStr="0"+year;
                        }else{
                            yearStr=""+year;
                        }
                        if(month<10){
                            etTimeStart.setText(yearStr + ":0" + month);
                        }else{
                            etTimeStart.setText(yearStr + ":" + month);
                        }
                    }
                });
                ageDialog2.show();
                break;
        }
    }

    private String startDate, endDate, startTime, endTime;

    private void payOrder(final int payType) {
        loadingDialog.show();
        OkgoUtil.post(Http.PlaceOrder, ConfirmOrderActivity.this)
                .params("curruserid", curruserId)
                .params("labelid", labeId)
                .params("labeltype", labelType)
                .params("startdate", startDate)
                .params("starttime", startTime)
                .params("enddate", "")
                .params("endtime", "")
                .params("paytype", payType)
                .params("order_area", order_area)
                .params("timetype", timetype)
                .params("selectnum", selectnum)
                .params("rewardprice", rewardPrice + cusPrice)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                            switch (payType){
                                case 1:
                                    AliPayResBean parentBean = DealResult.getInstance().dealDatas(ConfirmOrderActivity.this
                                            , response, new TypeToken<AliPayResBean>() {
                                            }.getType());
                                    if (parentBean == null) {
                                        return;
                                    }
                                    if(parentBean.getCode()==Constant.SUCESS){
                                        AliPayUtiles utiles = new AliPayUtiles(ConfirmOrderActivity.this, parentBean.getBody());
                                        utiles.setOnResultListener(new AliPayUtiles.PayResultOnListener() {
                                            @Override
                                            public void getResult(Boolean result) {
                                                if (result) {
                                                    Intent i=new Intent(ConfirmOrderActivity.this, MainActivity.class);
                                                    i.putExtra("type",1);
                                                    startActivity(i);
                                                    ToastUtils.toastForShort(ConfirmOrderActivity.this,"下单成功");
//                                                    ConfirmOrderActivity.this.finish();
                                                }
                                            }
                                        });
                                        utiles.startPay();
                                    }
                                    ToastUtils.toastForShort(ConfirmOrderActivity.this, parentBean.getResult());
                                break;
                            case 2:
                                WXPAtResultBean wxParentBean = DealResult.getInstance().dealDatas(ConfirmOrderActivity.this
                                        , response, new TypeToken<WXPAtResultBean>() {
                                        }.getType());
                                if (wxParentBean == null) {
                                    return;
                                }
                                if(wxParentBean.getCode()==Constant.SUCESS) {
                                    WeChatPayUtiles weChatPayUtiles = new WeChatPayUtiles(ConfirmOrderActivity.this);
                                    weChatPayUtiles.WXPay(wxParentBean.getBody());
                                }
                                ToastUtils.toastForShort(ConfirmOrderActivity.this, wxParentBean.getResult());
                                break;
                            }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

    private void countTotalPrice() {
        loadingDialog.show();
        OkgoUtil.post(Http.HandleTotal, ConfirmOrderActivity.this)
                .params("curruserid", curruserId)
                .params("labelid", labeId)
                .params("labeltype", labelType)
                .params("startdate", startDate)
                .params("starttime", startTime)
                .params("enddate", endDate)
                .params("endtime", endTime)
                .params("selectnum", selectnum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDialog.dismiss();
                        TotalPriceBean parentBean = DealResult.getInstance().dealDatas(ConfirmOrderActivity.this, response, new TypeToken<TotalPriceBean>() {
                        }.getType());
                        if (parentBean == null) {
                            return;
                        }
                        if (parentBean.getCode() == Constant.SUCESS) {
                            countPrice = parentBean.getBody().getTotal();
                            totalPrice = countPrice+rewardPrice+cusPrice;
                            tvConfirm.setText("提交订单(共计" + totalPrice + "元)");
                        } else {
                        }
//                        ToastUtils.toastForShort(ConfirmOrderActivity.this, parentBean.getResult());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDialog.dismiss();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.CITY_RESULT:
                tvAdress.setText(data.getStringExtra("address"));
                break;
        }
    }


}
